<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="优惠券兑换码" prop="couponCode">
        <el-input
          v-model="queryParams.couponCode"
          placeholder="请输入优惠券兑换码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="优惠券数量" prop="couponNum">
        <el-input
          v-model="queryParams.couponNum"
          placeholder="请输入优惠券数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="优惠券金额" prop="money">
        <el-input
          v-model="queryParams.money"
          placeholder="请输入优惠券金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="最低消费金额" prop="minSpend">
        <el-input
          v-model="queryParams.minSpend"
          placeholder="请输入最低消费金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="有效开始时间" prop="startDate">
        <el-date-picker clearable
                        v-model="queryParams.startDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择有效开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="有效结束时间" prop="endDate">
        <el-date-picker clearable
                        v-model="queryParams.endDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择有效结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="优惠券使用状态" prop="state">
        <el-input
          v-model="queryParams.state"
          placeholder="请输入优惠券使用状态"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="优惠券使用时间" prop="userTime">
        <el-date-picker clearable
                        v-model="queryParams.userTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择优惠券使用时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="医生id" prop="doctorId">
        <el-input
          v-model="queryParams.doctorId"
          placeholder="请输入医生id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="药品id" prop="medicalMedicineId">
        <el-input
          v-model="queryParams.medicalMedicineId"
          placeholder="请输入药品id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['coupon:coupon:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['coupon:coupon:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['coupon:coupon:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['coupon:coupon:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="couponList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="优惠券兑换码" align="center" prop="couponCode" />
      <el-table-column label="优惠券类型" align="center" prop="couponType">
        <template slot-scope="scope">
          <span v-if="scope.row.couponType==0">全场通用</span>
          <span v-if="scope.row.couponType==1">药品专用</span>
          <span v-if="scope.row.couponType==2">咨询专用</span>
        </template>
      </el-table-column>
      <el-table-column label="优惠券数量" align="center" prop="couponNum" />
      <el-table-column label="优惠券金额" align="center" prop="money" />
      <el-table-column label="最低消费金额" align="center" prop="minSpend" />
      <el-table-column label="有效开始时间" align="center" prop="startDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="有效结束时间" align="center" prop="endDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="优惠券使用状态" align="center" prop="state">
        <template slot-scope="scope">
          <span v-if="scope.row.state==0">待使用</span>
          <span v-if="scope.row.state==1">已使用</span>
          <span v-if="scope.row.state==2">已过期</span>
        </template>
      </el-table-column>
      <el-table-column label="优惠券使用时间" align="center" prop="userTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.userTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="医生id" align="center" prop="doctorId" />
      <el-table-column label="药品id" align="center" prop="medicalMedicineId" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['coupon:coupon:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['coupon:coupon:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改coupon对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form :model="form" ref="couponForm">
          <el-form-item label="优惠券兑换码" prop="couponCode">
            <el-input v-model="form.couponCode" placeholder="请输入或生成优惠券兑换码" />
            <el-button type="text" @click="generateCode" v-if="!isGenerating">生成兑换码</el-button>
            <el-button type="text" @click="resetCode" v-if="isGenerating">重置</el-button>
          </el-form-item>
        </el-form>
        <el-form-item label="优惠券数量" prop="couponNum">
          <el-input-number  :min="1" :max="10" v-model="form.couponNum" placeholder="请输入优惠券数量" />
        </el-form-item>
        <el-form-item label="优惠券金额" prop="money">
          <el-input-number :min="10" :max="100" v-model="form.money" placeholder="请输入优惠券金额" />
        </el-form-item>
        <el-form-item label="最低消费金额" prop="minSpend">
          <el-input-number :min="50" :max="500" v-model="form.minSpend" placeholder="请输入最低消费金额" />
        </el-form-item>
        <el-form-item label="优惠券类型" prop="couponType">
          <el-select v-model="form.couponType" placeholder="请选择优惠券类型">
            <el-option label="全场通用" value="0"></el-option>
            <el-option label="药品专用" value="1"></el-option>
            <el-option label="咨询专用" value="2"></el-option>
            <!-- 根据实际情况添加更多选项 -->
          </el-select>
        </el-form-item>
        <el-table
          ref="multipleTable"
          :data="doctorTableData"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange" v-if="form.couponType==2">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="id" align="center" prop="id" />
          <el-table-column label="医生姓名" align="center" prop="name" />
          <el-table-column label="医生性别" align="center" prop="sex" />
          <el-table-column label="出生日期" align="center" prop="birthDate" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.birthDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="联系方式" align="center" prop="phone" />
          <el-table-column label="居住地址" align="center" prop="address" />
          <el-table-column label="医生执业证书编号" align="center" prop="licenseNumber" />
          <el-table-column label="执业证书发放日期" align="center" prop="licenseissueDate" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.licenseissueDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="执业证书到期日期" align="center" prop="licenseExpireDate" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.licenseExpireDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="所属医院id" align="center" prop="hospitalId" />
          <el-table-column label="科室id" align="center" prop="departmentId" />
          <el-table-column label="个人简介" align="center" prop="bio" />
          <el-table-column label="医生图片" align="center" prop="profilePic" width="100">
            <template slot-scope="scope">
              <image-preview :src="scope.row.profilePic" :width="50" :height="50"/>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="status"/>
        </el-table>
        <el-table
          ref="multipleTable"
          :data="medicineTableData"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange" v-if="form.couponType==1">
          <el-table-column
            type="selection"
            width="55"
          ></el-table-column>
          <!-- 其他列 -->
          <el-table-column
            label="编号"
            width="180">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.id }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="药品名称"
            width="180">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="图片"
            width="180">
            <template slot-scope="scope">
              <el-image
                style="width: 100px; height: 100px"
                :src="scope.row.pic"
              ></el-image>
            </template>
          </el-table-column>
          <el-table-column
            label="单价"
            width="180">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.price }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="实际销售单价"
            width="180">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.actualSalesUnitPrice }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="主治功能"
            width="180">
            <template slot-scope="scope" v-if="null != scope.row.indicativeFunctions ">
              <span style="margin-left: 10px" v-if="scope.row.indicativeFunctions.length > 10">{{ scope.row.indicativeFunctions.slice(0, 10) + '***' }}</span>
              <span style="margin-left: 10px" v-else>{{ scope.row.indicativeFunctions }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="用法用量"
            width="180">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.usagAndDosage }}</span>
            </template>
          </el-table-column>

          <el-table-column
            label="所属药房"
            width="180">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.pharmacyId }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="药品规格"
            width="180">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.sku }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="运费"
            width="180">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.shippingFee }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="生产企业"
            width="180">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.manufacturingEnterprise }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="药品成分"
            width="180">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.drugIngredients }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="用药禁忌"
            width="180">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.contraindications }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="药品性状"
            width="180">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.drugShape }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="不良反应"
            width="180">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.adverseReactions }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="相互作用"
            width="180">
            <template slot-scope="scope" v-if="null != scope.row.interact ">
              <span style="margin-left: 10px" v-if="scope.row.interact.length > 10">{{ scope.row.interact.slice(0, 10) + '***' }}</span>
              <span style="margin-left: 10px" v-else>{{ scope.row.interact }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="贮藏条件"
            width="180">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.storageConditions }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="包装"
            width="180">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.packages }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="剂型"
            width="180">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.dosageForm }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="注意事项"
            width="180">
            <template slot-scope="scope" v-if="null != scope.row.precautions ">
              <span style="margin-left: 10px" v-if="scope.row.precautions.length > 10">{{ scope.row.precautions.slice(0, 10) + '***' }}</span>
              <span style="margin-left: 10px" v-else>{{ scope.row.precautions }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="批准文号"
            width="180">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.approvalNo }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="药品类型"
            width="180">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.typeId }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="库存"
            width="180">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.inventory }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="销量"
            width="180">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.salesVolume }}</span>
            </template>
          </el-table-column>
          <el-table-column label="生产日期" align="center" prop="dateOfManufacture" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.dateOfManufacture, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="有效期" align="center" prop="periodOfValidity" />
          <el-table-column label="最后修改时间" align="center" prop="lastUpdateTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.lastUpdateTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="排序字段" align="center" prop="sort" />
          <el-table-column label="逻辑删除字段" align="center" prop="isDeleted" />
          <el-table-column label="上架状态" align="center" prop="status" />
          <el-table-column label="过期状态" align="center" prop="pastDue" />
        </el-table>
        <el-form-item label="有效开始时间" prop="startDate">
          <el-date-picker
            clearable
            v-model="form.startDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择有效开始时间"
            :picker-options="startDatePickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="有效结束时间" prop="endDate">
          <el-date-picker
            clearable
            v-model="form.endDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择有效结束时间"
            :picker-options="endDatePickerOptions">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCoupon,
  getCoupon,
  delCoupon,
  addCoupon,
  updateCoupon,
  listDoctorCoupon,
  listMedicineCoupon
} from "@/api/coupon/coupon";

export default {
  name: "Coupon",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // coupon表格数据
      couponList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        couponCode: null,
        couponType: null,
        couponNum: null,
        money: null,
        minSpend: null,
        startDate: null,
        endDate: null,
        state: null,
        userTime: null,
        doctorId: null,
        medicalMedicineId: null,
      },
      // 表单参数
      form: {},
      doctorTableData:[],
      medicineTableData:[],
      // 表单校验
      rules: {
      },
      generatedCode: '',
      isGenerating: false,
      startDatePickerOptions: {
        disabledDate(time) {
          // 禁止选择今天之前的日期和未来某个日期之后的日期（这里仅作为示例）
          return time.getTime() < Date.now() - 86400000 || time.getTime() > new Date('2030-12-31').getTime();
        }
      },
      endDatePickerOptions: {
        disabledDate:(time) =>{
          // 禁止选择开始时间之前的日期和未来某个日期之后的日期（同时考虑已选择的开始时间）
          return time.getTime() < this.form.startDate || time.getTime() > new Date('2030-12-31').getTime();
        }
      },
      userTimePickerOptions: {
        disabledDate:(time) => {
          // 禁止选择开始时间之前和结束时间之后的日期
          const startDate = this.form.startDate ? new Date(this.form.startDate) : null;
          const endDate = this.form.endDate ? new Date(this.form.endDate) : null;
          if (!startDate || !endDate) {
            // 如果开始时间或结束时间未选择，则不进行限制（或你可以设置其他限制）
            return false;
          }
          return time.getTime() < startDate.getTime() || time.getTime() > endDate.getTime();
        }
      }
    };
  },
  created() {
    this.getList();
    this.getDoctor();
    this.getMedicine();
  },
  methods: {
    /** 查询coupon列表 */
    getList() {
      this.loading = true;
      listCoupon(this.queryParams).then(response => {
        this.couponList = response.data.rows;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        couponCode: null,
        couponType: null,
        couponNum: null,
        money: null,
        minSpend: null,
        startDate: null,
        endDate: null,
        state: null,
        userTime: null,
        doctorId: null,
        medicalMedicineId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加coupon";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCoupon(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改coupon";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            this.form.ids=this.ids
            updateCoupon(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.ids=this.ids
            console.log(this.ids)
            addCoupon(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除coupon编号为"' + ids + '"的数据项？').then(function() {
        return delCoupon(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('coupon/coupon/export', {
        ...this.queryParams
      }, `coupon_${new Date().getTime()}.xlsx`)
    },
    generateCode() {
      const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
      let result = '';
      const charactersLength = characters.length;
      for (let i = 0; i < 16; i++) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
      }
      this.generatedCode = result;
      this.form.couponCode = result;
      this.isGenerating = true; // 设置已生成兑换码的状态
    },
    resetCode() {
      this.form.couponCode = '';
      this.generatedCode = '';
      this.isGenerating = false; // 重置为未生成兑换码的状态
    },
    getDoctor(){
      listDoctorCoupon().then(res=>{
        this.doctorTableData=res.data
      })
    },
    getMedicine(){
      listMedicineCoupon().then(res=>{
        this.medicineTableData=res.data
      })
    }
  }
};
</script>
